package sword.T29;

/**
 * @Author: 18362
 * @Create: 2022-04-01 12:20:17 星期五
 */
class Solution {

    private static int[] dx = {0, 1, 0, -1};
    private static int[] dy = {1, 0, -1, 0};
    public int[] spiralOrder(int[][] matrix) {
        int m = matrix.length;
        if (m == 0)
            return new int[]{};
        int n = matrix[0].length;
        int[] res = new int[m*n];
        if (m*n == 0)
            return res;
        boolean[][] vis = new boolean[m][n];
        int x = 0, y = 0, k = 0, dir = 0;
        while (true) {
            res[k++] = matrix[x][y];
            if (k == res.length)
                break;
            vis[x][y] = true;
            int nx = x + dx[dir], ny = y + dy[dir];
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny]) {
                x = nx;
                y = ny;
            } else {
                dir = (dir+1) % 4;
                x = x + dx[dir];
                y = y + dy[dir];
            }
        }
        return res;
    }
}